package com.ccb;



/**
 * 基于字节数组的字节包类，封装了字节操作<br>
 * <br>
 * 提供追加一个字节<br>
 * 提供追加字节数组<br>
 * 提供追加BytePackage<br>
 * 提供返回字节数组<br>
 * 提供返回长度<br>
 * 提供清空<br>
 * 
 * 
 * @author lijic
 * 
 */
public class BytePackage {
	private byte[] m_bytes = new byte[128];
	private int m_pos = 0;

	public BytePackage Append(byte b) {
		this.ensureSize(1);
		this.m_bytes[this.m_pos++] = b;
		return this;
	}

	/**
	 * 追加字节数组<br>
	 * 处理步骤:<br>
	 * 如果为null,则直接返回原来的BytePackage<br>
	 * 否则将字节数组中的每个字节加入到对象的m_bytes中<br>
	 * 
	 * @param bytes
	 *            字节数组
	 * @return BytePackage字节包
	 */
	public BytePackage Append(byte[] bytes) {
		if (bytes == null)
			return this;

		this.ensureSize(bytes.length);
		System.arraycopy(bytes, 0, this.m_bytes, this.m_pos, bytes.length);
		this.m_pos += bytes.length;
		return this;
	}

	public BytePackage Append(Byte[] bytes) {
		if (bytes == null)
			return this;

		this.ensureSize(bytes.length);
		System.arraycopy(bytes, 0, this.m_bytes, this.m_pos, bytes.length);
		this.m_pos += bytes.length;
		return this;
	}

	public BytePackage Append(byte[] bytes,int length)
	{
		if (bytes == null)
			return this;

		this.ensureSize(length);
		System.arraycopy(bytes, 0, this.m_bytes, this.m_pos, length);
		this.m_pos += bytes.length;
		return this;
	}
	public BytePackage Append(BytePackage p) {
		if (p == null)
			return this;

		this.Append(p.getbytes());
		return this;
	}

	public byte[] getbytes() {
		if (this.m_bytes.length > this.m_pos) {
			byte[] bytes = new byte[this.m_pos];
			System.arraycopy(this.m_bytes, 0, bytes, 0, this.m_pos);
			this.m_bytes = bytes;
		}
		return this.m_bytes;
	}

	public int length() {
		return this.m_pos;
	}

	public void Clear() {
		this.m_bytes = new byte[1024];
	}

	/**
	 * 
	 * @param i
	 * @param put_int32
	 */
	public void Replace(int start, byte[] bytes) {
		this.ensureSize(start + bytes.length);
		for (int i = 0; i < bytes.length; i++)
			this.m_bytes[start + i] = bytes[i];
	}

	private void ensureSize(int len) {
		if (this.m_pos + len > this.m_bytes.length) {
			byte[] bytes = new byte[(this.m_bytes.length + len) * 2];
			System.arraycopy(this.m_bytes, 0, bytes, 0, this.m_pos);
			this.m_bytes = bytes;
		}
	}
}
